package com.xw.netty.basic;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 服务器端的业务处理类
 * @ClassName NettyServerHandler
 * @Author liu zhiyong
 * @Date 2020/8/20 15:53
 * @Version 1.0
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter{

    // 用来保存所有的客户端连接
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 读取数据事件
     * @param ctx
     * @param msg
     * @return void
     **/
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        System.out.println("Server:" + ctx);
        ByteBuf buf = (ByteBuf)msg;
        System.out.println("from客户端[" + ctx.channel().id() + "]发来的数据" +  buf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 数据读取完成事件
     * @param ctx
     * @return void
     **/
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("from Server: get your[" + ctx.channel().id() + "] message...", CharsetUtil.UTF_8));
    }

    /**
     * 通道就绪（当有新的客户端连接服务器之后，会自动调用这个方法）
     * @param ctx
     * @return void
     **/
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 将新的通道加入到clients
        clients.add(ctx.channel());
        System.out.println(ctx.channel().id() + "新客户端连接成功...");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().id() + "客户端断开连接...");
    }

    /**
     * 异常发生事件
     * @param ctx
     * @param cause
     * @return void
     **/
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exception异常...");
        ctx.close();
    }


}
